#include "TestPicShowWidget.h"
#include "ui_TestPicShowWidget.h"
#include <opencv2/core/mat.hpp>
#include <opencv2/imgproc.hpp>
#include <qimage.h>

#include <QDebug>
#include <qpixmap.h>

#include "spdlog/spdlog.h"

TestPicShowWidget::TestPicShowWidget(QWidget *parent)
    : QWidget(parent), ui(new Ui::TestPicShowWidget) {
  ui->setupUi(this);

  last_time_1_ = std::chrono::high_resolution_clock::now();
  last_time_2_ = std::chrono::high_resolution_clock::now();

  timer_ = new QTimer(this);
  connect(timer_, &QTimer::timeout, this, [this]() { _check_active(); });
  timer_->start(200);
}

TestPicShowWidget::~TestPicShowWidget() { delete ui; }

void TestPicShowWidget::_check_active() {
  constexpr int interval_max = 1500;

  auto now = std::chrono::high_resolution_clock::now();
  auto duration =
      std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time_1_);
  _set_label_active(ui->lb_active_1, duration.count() <= interval_max);

  duration =
      std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time_2_);
  _set_label_active(ui->lb_active_2, duration.count() <= interval_max);
}

void TestPicShowWidget::_set_label_active(QLabel *label, bool active) {
  if (active) {
    label->setText(tr("ACTIVE!!"));
    // label->setStyleSheet("border: 2px solid red");
    label->setStyleSheet("QLabel{ border: 2px solid red; background-color: rgb(0, 238, 118) }");
  } else {
    label->setText(tr("INACTIVE"));
    label->setStyleSheet("QLabel{ border: 2px solid black; background-color: gray }");
  }
}

void TestPicShowWidget::show_pic(int num, const cv::Mat &mat) {
  using namespace cv;

  if (num != 1 && num != 2) {
    return;
  }

  // spdlog::debug("num: {}, mat.cols: {}, mat.rows: {}", num, mat.cols, mat.rows);

  Mat dst;
  cvtColor(mat, dst, COLOR_BGR2RGB);
  if (num == 1) {
    cv::resize(dst, dst,
               Size{ui->lb_pic1->size().width(), ui->lb_pic1->size().height()});
  } else {
    cv::resize(dst, dst,
               Size{ui->lb_pic2->size().width(), ui->lb_pic2->size().height()});
  }

  QImage img = QImage(dst.data, dst.cols, dst.rows, dst.channels() * dst.cols,
                      QImage::Format_RGB888);

  QPixmap pixmap = QPixmap::fromImage(img);

  if (num == 1) {
    ui->lb_pic1->setPixmap(pixmap);
    ++cnt_1_;
    ui->lb_cnt_1->setText(QString("cnt: %1").arg(cnt_1_));
    last_time_1_ = std::chrono::high_resolution_clock::now();
  } else {
    ui->lb_pic2->setPixmap(pixmap);
    ++cnt_2_;
    ui->lb_cnt_2->setText(QString("cnt: %1").arg(cnt_2_));
    last_time_2_ = std::chrono::high_resolution_clock::now();
  }

  _check_active();
}
